package com.shigen.demo.pattern.singleton;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 容器式单例
 *
 * @author shigenfu
 * @date 2022/8/14 2:18 下午
 */
public class ContainerSingleton {

  private ContainerSingleton() {

  }

  private static Map<String, Object> ioc = new ConcurrentHashMap<>();

  public static Object getInstance(String className) {
    synchronized (ioc) {
      if (!ioc.containsKey(className)) {
        Object obj = null;
        try {
          obj = Class.forName(className).newInstance();
          ioc.put(className, obj);
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
          e.printStackTrace();
        }
        return obj;
      } else {
        return ioc.get(className);
      }
    }
  }
}
